package com.qf.mq.hello;

import com.qf.mq.utils.MqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import java.io.IOException;

public class Recv {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception {
        final Connection connection = MqUtils.getConnection();
        final Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        // 当消息队列中有消息推送给当前消费者时，会回调这个接口的方法
        final DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                final String s = new String(message.getBody(), "utf-8");
                System.out.println("消费者消费消息:"+s);
            }
        };

        /**
         * 让当前消费者去消费指定的队列中的消息
         * @param queue the name of the queue
         * @param autoAck 如果true，代表消息一旦送到消费者端，消费者就马上确认了该消息，消息一旦被消费者确认，就会从mq服务器端删除掉
         * acknowledged once delivered; false if the server should expect
         * explicit acknowledgements
         * @param deliverCallback callback when a message is delivered
         * @param cancelCallback callback when the consumer is cancelled
         */
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });

    }
}
